<template>
  <div class="insert-image" v-loading.fullscreen.lock="loading">
    <div style="margin-bottom:5px">
      <el-input style="width:calc(100% - 65px)" v-model="searchValue" size="small" placeholder="请输入搜索条件">
        <el-button slot="append" icon="el-icon-search" @click="searchData"></el-button>
      </el-input>
      <el-button type="primary" size="small" @click="ensure">确定</el-button>
    </div>
    <div class="insert-image-content">
      <template v-for="image in imageList">
        <div :key="image.id">
          <el-checkbox :key="image.id" v-model="image.checked">
          </el-checkbox>
          <el-image :src="image.url" fit="scale-down" :preview-src-list="[image.url]"></el-image>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
  import GoodsApi from 'services/goodsApi';

  export default {
    props: {
      queryValue: {
        type: String,
        default: ''
      }
    },

    data() {
      return {
        loading: false,
        searchValue: this.queryValue,
        imageList: []
      };
    },

    created() {
      let searchValue = this.searchValue;
      if (searchValue.trim() === '') {
        return;
      }
      this.searchData();
    },

    methods: {
      searchData() {
        let searchValue = this.searchValue;
        if (searchValue.trim() === '') {
          this.$alert('请输入搜索条件');
          return;
        }

        this.loading = true;
        GoodsApi.getGoodsImage(searchValue).then(imageList => {
          this.imageList = imageList;
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        });
      },

      ensure() {
        let imageList = this.imageList;
        imageList = _.filter(imageList, {
          checked: true
        });
        if (imageList.length === 0) {
          this.$alert('请输入需要插入的图片', '信息');
          return;
        }

        this.loading = true;
        GoodsApi.uploadGoodsImgList(imageList).then(imgDataList => {
          this.$emit('insert-img', imgDataList);
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        });
      }
    }
  };

</script>

<style lang="scss" scoped>
  .insert-image {
    padding: 0 10px 5px;
    height: calc(100% - 5px);

    .insert-image-content {
      height: calc(100% - 37px);
      overflow: auto;

      >div {
        float: left;
        margin-right: 10px;
        margin-bottom: 10px;

        .el-checkbox {
          vertical-align: top;
          margin-right: 5px;
        }

        .el-image {
          width: 80px;
          height: 80px;
        }
      }
    }
  }

</style>
